/*
 * LexOrderedList.java
 *
 * Created on February 8, 2004, 10:14 PM
 */

package com.milowski.monos.monomial;

import java.util.*;
import com.milowski.monos.*;
import org.infoset.xml.InfosetFactory;
import org.infoset.xml.ItemConstructor;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.XMLException;

/**
 * A list that is lexicographically ordered.
 * @author  R. Alexander Milowski
 */
public class LexOrderedList extends ArrayList implements LexOrdered,XMLMarshaller {

   protected LexOrder order;
   /** 
    * Creates a new instance with the lexicographic ordering given.
    * @param order The ordering to use.
    */
   public LexOrderedList(LexOrder order) {
      this.order = order;
   }
   
   /**
    * Returns the lexicographic ordering associated with this list.
    */
   public LexOrder getLexOrder() {
      return order;
   }
   
   public String toString() {
      return toString(null);
   }
   
   public String toString(LexOrder inScopeOrder) {
      StringBuffer sb = new StringBuffer();
      if (inScopeOrder==order) {
         sb.append("(lexed-list \n");
      } else {
         sb.append("(lexed-list-with-order ");
         sb.append(order.toString());
         sb.append("\n");
      }
      
      for (Iterator toOutput=iterator(); toOutput.hasNext();) {
         Object o = toOutput.next();
         if (o instanceof Monomial) {
            sb.append(((Monomial)o).format(order));
         } else if (o instanceof LexOrdered) {
            sb.append(((LexOrdered)o).toString(order));
         } else {
            sb.append(o.toString());
         }
         if (toOutput.hasNext()) {
            sb.append('\n');
         }
      }              
      sb.append(')');
      return sb.toString();
   }
   
   public void toXML(ItemDestination dest) throws XMLException {
      toXML(InfosetFactory.getDefaultInfoset().createItemConstructor(),dest);
   }

   public void toXML(ItemConstructor constructor, ItemDestination dest) throws XMLException {
      dest.send(constructor.createElement(XML.lexedListName));
      order.toXML(constructor,dest);
      for (Iterator contents=iterator(); contents.hasNext(); ) {
         Object o = contents.next();
         if (o instanceof XMLMarshaller) {
            ((XMLMarshaller)o).toXML(constructor,dest);
         } else {
            throw new XMLException("Class "+o.getClass().getName()+" cannot be marshalled into XML.");
         }
      }
      dest.send(constructor.createElementEnd(XML.lexedListName));
   }
   
}
